package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.CartItem;
import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.domain.Product;
import csu.web.mypetstore.persistence.AccountDao;
import csu.web.mypetstore.persistence.ItemDao;
import csu.web.mypetstore.persistence.impl.AccountDaoImpl;
import csu.web.mypetstore.persistence.impl.ItemDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;

public class AddItemToCartAJAXServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String itemId = req.getParameter("itemId");

        HttpSession session = req.getSession();
        AccountDao accountDao = new AccountDaoImpl();
        Account loginAccount = (Account) session.getAttribute("loginAccount");

        System.out.println(itemId);
        CartItem cartItem = new CartItem();
        ItemDao itemDao = new ItemDaoImpl();
        Item item = itemDao.getItem(itemId);
        cartItem.setItem(item);
        Product product = item.getProduct();
        item.setProduct(product);
        String listprice = String.valueOf(item.getListPrice());
        Double listpriceDouble = Double.parseDouble(listprice);

        if(loginAccount != null) {
            if(accountDao.selectShoppingcartByUsernameAndItemIdAndTimes(loginAccount,cartItem)){
                System.out.println("Shoppingcart already exist");
                int q = accountDao.selectQuantityByUsernameAndItemid(loginAccount,cartItem);
                cartItem.setQuantity(q+1);
                cartItem.setTotal(BigDecimal.valueOf(cartItem.getQuantity()*listpriceDouble));
                accountDao.updateShoppingcartByUsernameAndItemid(loginAccount,cartItem);
            }
            else {
                System.out.println("Shoppingcart no exist");
                cartItem.setQuantity(1);
                cartItem.setTotal(BigDecimal.valueOf(cartItem.getQuantity()*listpriceDouble));
                accountDao.insertShoppingcart(loginAccount,cartItem,item,product);
            }

        }

    }

}
